/*
 *  KeyGen.c
 *
 *  Generating rsa public/private keys
 *
 *  Created on: April/13/2011
 *          by: Arash Molavi Kakhki <arash@ccs.neu.edu>   
 */


#include <stdio.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>

#define rsaKeySize 1024

int main() 
{ 

/****************************************************************************************************/
/* Genereating a RSA key and saves the private and public keys to the disk
/****************************************************************************************************/

	RSA *rsa = RSA_generate_key(rsaKeySize, RSA_F4, NULL, NULL);

	if (rsa == NULL){
		printf("\n\nError occured while generating the key\n");
		return 0;
	}
	else{
		printf("\n\nKey generated!\n");
		printf("RSA size is: %d\n", RSA_size(rsa));	
	}

	FILE *keyfile_pri = fopen("rsakey_pri.pem", "w");
	FILE *keyfile_pub = fopen("rsakey_pub.pem", "w");

	PEM_write_RSAPrivateKey(keyfile_pri, rsa, NULL, NULL, NULL, NULL, NULL);
	PEM_write_RSAPublicKey(keyfile_pub , rsa, NULL, NULL, NULL, NULL, NULL);

	fclose(keyfile_pri);
	fclose(keyfile_pub);
	
	return 1;
}
